﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using G.Navigate;
using System.Text.RegularExpressions;
using G.Reader.Data;

namespace G.Reader.View
{
    public partial class FoldersPage : GBasePage
    {
        private const string FoldersFilter = "{\r   \"data\": (.+?)\r}";
        public FoldersPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(FoldersPage_Loaded);
        }

        void FoldersPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (GloabalData.Instance.Session == null)
            {
                var backStack = this.NavigationService.BackStack;
                foreach (var item in backStack)
                {
                    if (this.NavigationService.BackStack.Count() > 1)
                        this.NavigationService.RemoveBackEntry();
                }
                this.NavigationService.GoBack();
            }
        }

        Microsoft.Live.LiveConnectClient client;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (this.listbox.ItemsSource == null)
            {
                if (GloabalData.Instance.Session != null)
                {
                    this.RegisterLoading(null);
                    string path = null;
                    this.NavigationContext.QueryString.TryGetValue("path", out path);
                    string name = null;
                    if (this.NavigationContext.QueryString.TryGetValue("name", out name))
                    {
                        this.PageTitle.Text = name;
                    }
                    else
                    {
                        this.PageTitle.Text = "我的 SkyDrive";
                    }
                    client = new Microsoft.Live.LiveConnectClient(GloabalData.Instance.Session);
                    client.GetCompleted += new EventHandler<Microsoft.Live.LiveOperationCompletedEventArgs>(client_GetCompleted);
                    client.DownloadCompleted += new EventHandler<Microsoft.Live.LiveDownloadCompletedEventArgs>(client_DownloadCompleted);
                    client.DownloadProgressChanged += new EventHandler<Microsoft.Live.LiveDownloadProgressChangedEventArgs>(client_DownloadProgressChanged);
                    if (string.IsNullOrEmpty(path))
                    {
                        path = "me/skydrive";
                    }
                    path = string.Format("{0}/files", path);
                    client.GetAsync(path);
                }
            }
        }

        void client_DownloadProgressChanged(object sender, Microsoft.Live.LiveDownloadProgressChangedEventArgs e)
        {
            this.progress.Value = e.ProgressPercentage;
            this.txt_progress.Text = string.Format("{0:N2}MB/{1:N2}MB", e.BytesReceived * 1.0 / 1024 / 1024, e.TotalBytesToReceive * 1.0 / 1024 / 1024);
        }

        void client_DownloadCompleted(object sender, Microsoft.Live.LiveDownloadCompletedEventArgs e)
        {
            this.grid_progress.Visibility = System.Windows.Visibility.Collapsed;
            GloabalData.Instance.BookDataBase.AddBook(e.Result, book);
            MessageBox.Show("您下载的书籍已经加入书架");
        }

        void client_GetCompleted(object sender, Microsoft.Live.LiveOperationCompletedEventArgs e)
        {
            var match = Regex.Match(e.RawResult, FoldersFilter, RegexOptions.CultureInvariant);
            var str = match.Groups[1].Value;
            var aa = G.SkyDrive.API.Parser<G.SkyDrive.Domain.Folder[]>(match.Groups[1].Value);
            listbox.ItemsSource = aa;
            this.UnregisterLoading();
        }
        BookInfo book;
        private void listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listbox.SelectedItem != null)
            {
                G.SkyDrive.Domain.Folder f = listbox.SelectedItem as G.SkyDrive.Domain.Folder;
                switch (f.Type)
                {
                    case "album":
                    case "folder":
                        this.NavigationService.Navigate(string.Format("/View/FoldersPage.xaml?path={0}&name={1}", f.ID, f.Name));
                        break;
                    case "file":
                        bool isexit = false;
                        foreach (var item in GloabalData.Instance.BookDataBase.BookTable)
                        {
                            if (item.BookName == f.Name)
                            {
                                isexit = true;
                                break;
                            }
                        }
                        if (isexit)
                        {
                            if (MessageBox.Show("书架里已经有相同名字的书，是否任然下载并且保存该书？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                            {
                                DownLoadFile(f.ID, f.Name);
                            }
                        }
                        else
                            DownLoadFile(f.ID, f.Name);
                        break;
                    default:
                        break;
                }
                listbox.SelectedItem = null;
            }
        }

        private void DownLoadFile(string path, string name)
        {
            this.grid_progress.Visibility = System.Windows.Visibility.Visible;
            this.progress.Value = 0;
            book = new BookInfo() { BookName = name };
            this.client.DownloadAsync(string.Format("{0}/content", path));
            //this.RegisterLoading("正在下载"

        }
    }
}